import { AdManager } from "../ads/AdManager";
import { Tools } from "../common/Tools";
import { ANSWER_STATE_ENUM, BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../base/EnumIndex";
import { AudioManager1 } from "../manager/AudioManager1";
import { EventManager } from "../manager/EventManager";
import { LevelManager } from "../manager/LevelManager";
import { ResManager1 } from "../manager/ResManager1";
import { UIManager } from "../manager/UIManager";
import LevelPre_15 from "../game/Game_15/LevelPre_15";
import LevelPre_24 from "../game/Game_24/LevelPre_24";
import LevelPre_23 from "../game/Game_23/LevelPre_23";
import LevelPre_14 from "../game/Game_14/LevelPre_14";

const { ccclass, property } = cc._decorator;


@ccclass
export default class TipUI extends cc.Component {
    @property({ type: cc.Node, displayName: "背景" })
    bgNode: cc.Node = null;
    @property({ type: cc.Node, displayName: "view节点" })
    viewNode: cc.Node = null;

    @property({ type: cc.Button, displayName: "提示按钮" })
    tipBtn: cc.Button = null;
    @property({ type: cc.Button, displayName: "查看答案按钮" })
    keyBtn: cc.Button = null;

    @property({ type: cc.Node, displayName: "查看提示框" })
    tipBox: cc.Node = null;
    @property({ type: cc.Label, displayName: "提示Lab" })
    tipLab: cc.Label = null;
    @property({ type: cc.Node, displayName: "查看答案框" })
    keyBox: cc.Node = null;
    @property({ type: cc.Label, displayName: "答案Lab" })
    keyLab: cc.Label = null;

    @property(cc.Node)
    content: cc.Node = null;
    @property(cc.Node)
    closeBtn: cc.Node = null;

    @property({ type: cc.Button, displayName: "上一页按钮" })
    lastBtn: cc.Button = null;
    @property({ type: cc.Button, displayName: "下一页按钮" })
    nextBtn: cc.Button = null;


    isVideoKey: boolean = false;  //是否已经获得答案
    keyInfo: any = null;   //答案信息
    private isGameOver = false;
    onLoad() {
        EventManager.ins.on(EVENT_NAME_ENUM.OPEN_UI, this.openUI, this);
        AdManager.naoLiReportVideo(1, "查看答案");
    }
    protected onDestroy(): void {
        //继续
        let lvName = LevelManager.ins.getBundleName();
        if (lvName == "15_268") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_268")
            level15.resumeAni();
        }
        if (lvName == "15_271") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_271")
            level15.resumeAni();
        }
        if (lvName == "15_272") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_272")
            level15.resumeAni();
        }
        if (lvName == "15_279") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_279")
            level15.resumeAni();
        }
        if (lvName == "15_281") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_281")
            level15.resumeAni();
        }
        if (lvName == "15_287") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_287")
            level15.resumeAni();
        }
        if (lvName == "15_286") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_286")
            level15.resumeAni();
        }
        if (lvName == "15_288") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_288")
            level15.resumeAni();
        }
        if (lvName == "15_289") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_289")
            level15.resumeAni();
        }
        if (lvName == "15_299") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_299")
            level15.resumeAni();
        }
        if (lvName == "15_301") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_301")
            level15.resumeAni();
        }
        if (lvName == "15_302") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_302")
            level15.resumeAni();
        }
        if (lvName == "15_304") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_304")
            level15.resumeAni();
        }
        if (lvName == "15_305") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_305")
            level15.resumeAni();
        }
        if (lvName == "15_308") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_308")
            level15.resumeAni();
        }
        if (lvName == "15_307") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_307")
            level15.resumeAni();
        }
        if (lvName == "15_290") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_290")
            level15.resumeAni();
        }
        if (lvName == "15_309") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_309")
            level15.resumeAni();
        }
        if (lvName == "15_317") {
            let level15 = cc.director.getScene().getChildByName("Canvas").getComponentInChildren("Level_15_317")
            level15.resumeAni();
        }
        EventManager.ins.off(EVENT_NAME_ENUM.OPEN_UI, this.openUI, this);
        this.unscheduleAllCallbacks();
    }
    // keyData 答案信息
    public openUI(keyData: any, isOpenBox = false, isGameOver = false) {
        this.keyInfo = keyData;
        this.isGameOver = isGameOver;
        cc.log(keyData)

        this.initUI();
        if (isOpenBox) {
            this.openKeyBox();
        }
        EventManager.ins.emit(EVENT_NAME_ENUM.OPEN_TIP_UI, true);
    }

    /** 初始化按钮 */
    initUI() {
        if (!this.keyInfo) {
            return;
        }
        if (this.keyInfo["keyStepInfo"] || this.keyInfo["keyProgressInfos"] || this.keyInfo["keyProgressInfos2"] || this.keyInfo["keyStepInfo14"]) {
            this.openTipBox();
            this.keyBtn.node.active = false;
            return;
        }

        let answerState = LevelManager.ins.getAnswerState();
        switch (answerState) {
            case ANSWER_STATE_ENUM.LOCKED:
                Tools.setSpriteState(this.keyBtn.node, 1, true);
                this.keyBtn.getComponent(cc.Button).interactable = false;
                break;
            case ANSWER_STATE_ENUM.UNLOCK_TIP:
                this.openTipBox();
                break;
            case ANSWER_STATE_ENUM.UNLOCK_ANSWER:
                this.openKeyBox();
                break;
            default:
                break;
        }
    }

    /** 打开提示页面 */
    openTipBox() {
        this.tipBtn.node.active = false;
        this.keyBtn.interactable = true;
        Tools.setSpriteState(this.keyBtn.node, 0, true);

        this.tipBox.active = true;
        this.tipBox.opacity = 0;
        this.tipBox.scaleX = 0;
        this.tipBox.scaleY = 1;

        cc.tween(this.tipBox).to(0.2, { opacity: 255, scale: 1 }, { easing: cc.easing.backOut }).start();
        if (this.keyInfo["keyProgressInfos"]) {
            let level24 = cc.find("Canvas").getComponentInChildren(LevelPre_24);
            let progress = level24.progress;
            if (this.isGameOver) {
                progress--;
            }
            if (progress > this.keyInfo["keyProgressInfos"].length - 1) {
                this.tipLab.string = "暂无提示^-^";
                return;
            }
            this.tipLab.string = this.keyInfo["keyProgressInfos"][progress];
        } else if (this.keyInfo["keyProgressInfos2"]) {
            let level23 = cc.find("Canvas").getComponentInChildren(LevelPre_23);
            let progress = level23.progress;
            if (this.isGameOver) {
                progress--;
            }
            if (progress > this.keyInfo["keyProgressInfos2"].length - 1) {
                this.tipLab.string = "暂无提示^-^";
                return;
            }
            this.tipLab.string = this.keyInfo["keyProgressInfos2"][progress];
        } else if (this.keyInfo["keyStepInfo"]) {
            let level15 = cc.find("Canvas").getComponentInChildren(LevelPre_15);
            let finishArr = level15.finishStateArr;
            let getLose = level15.getLose();
            let getCharu = level15.getCharu();
            let meiyouchufaxiang = true
            for (let i = 0; i < this.keyInfo["keyStepInfo"].length; i++) {
                let item = this.keyInfo["keyStepInfo"][i];
                let key = Object.keys(item)[0];
                if (finishArr.indexOf(key) == -1) {
                    if (getLose) {
                        meiyouchufaxiang = false
                        this.tipLab.string = item[key] + "\n您已执行过失败项，请重新开始";
                    } else {
                        if (getCharu) {
                            for (let i = 0; i < this.keyInfo["keyCharuInfo"].length; i++) {
                                let item2 = this.keyInfo["keyCharuInfo"][i];
                                let key2 = Object.keys(item2)[0];
                                if (finishArr.indexOf(key2) == -1) {
                                    meiyouchufaxiang = false;
                                    this.tipLab.string = item2[key2];
                                    return;
                                }
                            }
                        } else {
                            meiyouchufaxiang = false;
                            this.tipLab.string = item[key];
                        }
                    }
                    return;
                }
            }
            if (meiyouchufaxiang) {
                this.tipLab.string = "你已完成所有前置触发项";
            }


        } else if (this.keyInfo["keyStepInfo14"]) {

            let level14 = cc.find("Canvas").getComponentInChildren(LevelPre_14);
            let finishArr = level14.finishStateArr;
            let getLose = level14.getLose();
            let getCharu = level14.getCharu();

            for (let i = 0; i < this.keyInfo["keyStepInfo14"].length; i++) {
                let item = this.keyInfo["keyStepInfo14"][i];
                let key = Object.keys(item)[0];
                if (finishArr.indexOf(key) == -1) {
                    if (getLose) {
                        this.tipLab.string = item[key] + "\n您已执行过失败项，请重新开始";
                    } else {
                        if (getCharu) {
                            for (let i = 0; i < this.keyInfo["keyCharuInfo"].length; i++) {
                                let item2 = this.keyInfo["keyCharuInfo"][i];
                                let key2 = Object.keys(item2)[0];
                                if (finishArr.indexOf(key2) == -1) {
                                    this.tipLab.string = item2[key2];
                                    return;
                                }
                            }
                        } else {
                            this.tipLab.string = item[key];
                        }
                    }
                    return;
                }
            }


        } else {
            this.tipLab.string = this.keyInfo.tipInfo;
        }
    }

    /** 打开答案页面 */
    openKeyBox() {
        this.closeBtn.active = false;
        this.tipBox.active = false;
        this.isVideoKey = true;
        this.keyBtn.interactable = false;
        this.keyBox.active = true;

        this.lastBtn.node.active = false;
        this.nextBtn.node.active = false;

        this.updateScrollView()

        this.keyBox.scale = 0;
        cc.tween(this.keyBox).to(0.25, { scale: 1 }, { easing: cc.easing.backOut }).start();
    }

    // 根据答案内容大小 适配高度
    async updateScrollView() {
        // 设计分辨率宽750  弹窗宽655 scrollView宽590
        const WIN_WIDTH = 750, KEYBOX_WIDTH = 655, SCROLLVIEW_WIDTH = 590;

        // 适应答案图的宽度充满scrollView
        let scrollViewWidth = this.content.parent.width;
        let keySprMaxWidth = 0;
        if (this.keyInfo.keySprUrl) {
            for (let i = 0; i < this.keyInfo.keySprUrl.length; i++) {
                let spf = await ResManager1.ins.loadRes(this.keyInfo.keySprUrl[i], cc.SpriteFrame, BUNDLE_TYPE_ENUM.LEVEL);
                let keySpr = Tools.newSprite(spf);
                this.content.addChild(keySpr);
                // 图片宽度 > 视图宽度
                if (keySpr.width > scrollViewWidth) {
                    // 屏幕宽度 > 适配后宽度
                    let newWidth = keySpr.width + (KEYBOX_WIDTH - SCROLLVIEW_WIDTH) + (WIN_WIDTH - KEYBOX_WIDTH);
                    // console.log(i, keySpr.width, scrollViewWidth, newWidth, cc.winSize.width)
                    if (cc.winSize.width > newWidth) {
                        keySprMaxWidth = Math.max(keySprMaxWidth, keySpr.width);
                    } else {
                        // 超出屏幕宽度 等比缩小
                        let scale = scrollViewWidth / keySpr.width;
                        keySpr.setContentSize(scrollViewWidth, keySpr.height * scale);
                        console.log("超出屏幕宽度，等比缩小", scale)
                    }
                }
            }
        }

        // 答案文字
        for (let i = 0; i < this.keyInfo.keyInfos.length; i++) {
            let keyLab = cc.instantiate(this.keyLab.node);
            keyLab.getComponent(cc.Label).string = this.keyInfo.keyInfos[i];
            keyLab.getComponent(cc.Label).overflow = cc.Label.Overflow.RESIZE_HEIGHT;
            // this.labItemArr.push(keyLab);
            keyLab.width = this.content.width;
            this.content.addChild(keyLab);
            // tipWidth = Math.max(keyLab.width, tipWidth);
        }


        this.scheduleOnce(() => {
            /** 有可适配的宽 */
            if (keySprMaxWidth > 0) {
                console.log('有可适配的宽图', keySprMaxWidth)
                this.content.width = keySprMaxWidth;
                this.content.parent.width = keySprMaxWidth;//scrollview 宽度修改为最宽图片的宽
                this.keyBox.width = this.content.parent.width + (KEYBOX_WIDTH - SCROLLVIEW_WIDTH);
            }

            // const MAX_KEYBOX_WIDTH = cc.view.getVisibleSize().width - (WIN_WIDTH - KEYBOX_WIDTH);
            // if (this.keyBox.width < MAX_KEYBOX_WIDTH) {
            //     this.keyBox.width = MAX_KEYBOX_WIDTH;
            //     let extraWidth = MAX_KEYBOX_WIDTH - this.keyBox.width;
            //     this.content.parent.width += extraWidth;
            //     this.content.width += extraWidth;
            //     for (let i = 0; i < this.content.children.length; i++) {
            //         const child = this.content.children[i];
            //         if (child.getComponent(cc.Sprite)) {
            //             // 等比放大
            //             let scale = (child.width + extraWidth) / child.width;
            //             child.width += extraWidth;
            //             child.height *= scale;
            //         }
            //     }
            // }

            const MAX_KEYBOX_HEIGHT = cc.view.getVisibleSize().height - 400;
            // cc.log('updateScrollView', cc.view.getVisibleSize().height, this.content.getContentSize(), this.content.parent.getContentSize())
            // content 的高度 延迟一帧获取
            if (this.content.height > this.content.parent.height) {
                // 超过最大高度
                if (this.content.height > MAX_KEYBOX_HEIGHT) {
                    cc.log('超过最大高度', MAX_KEYBOX_HEIGHT)
                    this.content.parent.height = MAX_KEYBOX_HEIGHT - 133;
                    this.keyBox.height = MAX_KEYBOX_HEIGHT;
                } else {
                    this.content.parent.setContentSize(this.content.getContentSize());
                    this.content.parent.getComponent(cc.ScrollView).vertical = false;
                    this.keyBox.height = this.content.parent.height + 133;
                    cc.log('未超过最大高度', this.keyBox.height)
                }
                if (this.keyBox.height > 719) {
                    let deltaY = (this.keyBox.height - 719) / 2;
                    this.keyBox.y -= deltaY;
                    if (this.keyBox.y < 0) this.keyBox.y = 0;
                }
            } else {
                this.content.parent.setContentSize(this.content.getContentSize());
                this.content.parent.getComponent(cc.ScrollView).vertical = false;
            }
        }, 0)
    }

    labItemArr: Array<cc.Node> = [];
    labContent: cc.Node = null;
    seeKeyIndex: number = 0;
    /** 正在看哪个答案的Lab */
    seeKeyLab(seeKeyIndex: number) {
        this.seeKeyIndex = seeKeyIndex;
        if (this.seeKeyIndex < 0) { this.seeKeyIndex = 0; }
        if (this.seeKeyIndex > this.labItemArr.length - 1) { this.seeKeyIndex = this.labItemArr.length - 1 }

        cc.Tween.stopAllByTarget(this.labContent);
        let seeNode = this.labItemArr[this.seeKeyIndex];
        let tempPos = Tools.getToNodePosForNode(seeNode, this.labContent.parent);
        cc.tween(this.labContent).by(0.3, { position: cc.v3(-tempPos.x, 0) }).start();

        this.lastBtn.node.active = true;
        this.nextBtn.node.active = true;
        if (this.seeKeyIndex <= 0) {
            this.lastBtn.node.active = false;
        } if (this.seeKeyIndex >= this.labItemArr.length - 1) {
            this.nextBtn.node.active = false;
        }

        this.updateScrollView();
    }


    clickBtnClose() {
        AudioManager1.playClick();
        if (this.isVideoKey) {
            EventManager.ins.emit(EVENT_NAME_ENUM.LOOK_ANSWER_TWEEN);
        }
        EventManager.ins.emit(EVENT_NAME_ENUM.OPEN_TIP_UI, false);
        UIManager.ins.close();
    }
    /** 点击提示按钮 */
    clickBtnTip() {
        AudioManager1.playClick();
        AdManager.showVideoAd(() => {
            LevelManager.ins.unlockLevelTip1();
            this.openTipBox();
        });
    }
    /** 点击答案按钮 */
    clickBtnAnswer() {
        AudioManager1.playClick();
        let idx = LevelManager.ins.getLvInfoIdx(LevelManager.ins.curLvInfo.type, LevelManager.ins.curLvInfo.lv) + 1;
        AdManager.reportVideo(2, idx, LevelManager.ins.curLvInfo.name);
        AdManager.naoLiReportVideo(2, "查看答案");
        AdManager.showVideoAd(() => {
            AdManager.reportOverVideo(idx, LevelManager.ins.curLvInfo.name);
            AdManager.naoLiReportVideo(3, "查看答案");
            AdManager.naoLiReportVideo(4, "查看答案");
            LevelManager.ins.unlockLevelTip2();
            this.openKeyBox();
        });
    }
    clickBtnLast() {
        AudioManager1.playClick();
        this.seeKeyLab((this.seeKeyIndex - 1));
    }
    clickBtnNext() {
        AudioManager1.playClick();
        this.seeKeyLab((this.seeKeyIndex + 1));
    }
}